/*
 * Copyright 2011.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opu.db.obj.vis.ui.client.i18n;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import org.opu.db.obj.vis.ui.util.ConfigPath;
import org.opu.db.obj.vis.ui.util.Logger;

/**
 * @author Yuriy Dunko
 */
public class AbstractI18N {

    private static final Map<String, ResourceBundle> bundles
			= new HashMap<String, ResourceBundle>();
    
    private static Logger logger = Logger.create(AbstractI18N.class);
	
    protected ResourceBundle bundle;

    public static ResourceBundle getBundle(String path, Locale locale) {
        ResourceBundle bundle = bundles.get(path);

        if (bundle == null){
            bundles.put(path, bundle = ResourceBundle.getBundle(path, locale));
            logger.info("New bundle have been created.");
        }
        
        return bundle;
    }

    public AbstractI18N(String path) {
        this(path, ConfigPath.getInstance().getLocale());
    }

    public AbstractI18N(String path, Locale locale){
        logger.info(path + ":" + locale);
        bundle = getBundle(path, locale);
    }

    public String get(String key){
        return bundle.getString(key);
    }

    public String getString(String key){
        return getSafe(key);
    }

    public String getSafe(String key){
        try {
            return get(key);
        } catch (Exception e) {
            logger.error("Can't get resource [" + key + "]: " + e);
            return key;
        }
    }

    public String get(String key, String defaultValue){
        try {
            return get(key);
        } catch (Exception e) {
            return defaultValue;
        }
    }
}
